package com.bianmaba.jobs.collection.processor;

import com.bianmaba.beans.datamanagement.DataRow;
import com.bianmaba.beans.datamanagement.DataTable;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

@Transactional
public class DtsDataProcessor extends AbstractProcessor {

    public void mergeSourceDatas(String taskInstanceId, DataTable table) {
        List<DataTable> olds = dataTableService.queryToList(new HashMap() {{
            put("projectId", table.getProjectId());
            put("interfaceType", table.getInterfaceType());
            put("dataType", table.getDataType());
        }});
        if (!olds.isEmpty()) {
            DataTable oldTable = olds.get(0);
            mergeRows(oldTable.getRows(), table.getRows());
            dataTableService.save(oldTable);
        } else {
            dataTableService.save(table);
        }
    }

    public void mergeStatistics(String taskInstanceId, DataTable table) {
        List<DataTable> olds = dataTableService.queryToList(new HashMap() {{
            put("projectId", table.getProjectId());
            put("interfaceType", table.getInterfaceType());
            put("dataType", table.getDataType());
        }});

        //如果数据表不存在则创建，如果存在则更新
        if (olds != null && !olds.isEmpty()) {
            DataTable old = olds.get(0);
            old.getRows().addAll(table.getRows());
        } else {
            dataTableService.save(table);
        }
    }


    private void mergeRows(List<DataRow> oldRows, List<DataRow> newRows) {
        for (DataRow newRow : newRows) {
            DataRow oldRow = findAndRemoveInOldRows(oldRows, newRow);
            if (oldRow != null) {
                oldRow.getDataItems().clear();
                oldRow.getDataItems().addAll(newRow.getDataItems());
            }
        }
        oldRows.addAll(newRows);
    }

    private DataRow findAndRemoveInOldRows(List<DataRow> oldRows, DataRow newRow) {
        Iterator<DataRow> iterator = oldRows.iterator();
        while (iterator.hasNext()) {
            DataRow row = iterator.next();
            String oldNo = row.getValue("问题单号");
            String newNo = newRow.getValue("问题单号");
            if (oldNo.equalsIgnoreCase(newNo)) {
                iterator.remove();
                return row;
            }
        }
        return null;
    }

}
